package com.example.wechattakeaway.security.relam;


import com.example.wechattakeaway.entity.SysUser;
import com.example.wechattakeaway.entity.UserRole;
import com.example.wechattakeaway.mapper.SysUserMapper;
import com.example.wechattakeaway.mapper.UserRoleMapper;
import com.example.wechattakeaway.service.RoleService;
import com.example.wechattakeaway.token.LoginToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    public static String realmName = "UserRealm";

    public static String getRealmName() {
        return realmName;
    }

    @Autowired
    SysUserMapper userMapper;

    @Resource
    UserRoleMapper roleMapper;

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行用户授权逻辑");
        Set<String> perms = new HashSet<>();
        SysUser user = (SysUser) principalCollection.getPrimaryPrincipal ();

        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //给资源添加授权字符串
//        info.addStringPermission("add");
//        Subject subject = SecurityUtils.getSubject();
//        User user = (User) subject.getPrincipal();
        info.setStringPermissions (user.getPerms());
        return info;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行用户认证逻辑");
        LoginToken token = (LoginToken) authenticationToken;
        //通过数据库获取包含token当中用户信息的用户
        SysUser user = userMapper.SelectUserByName (token.getUsername ());
        if (user == null){
            return null;
        }
        Set<String> perms = new HashSet<> ();
        UserRole userRole = new UserRole();
        //通过数据库获取用户权限
        userRole = roleMapper.SelectObjectById(user.getUserRole());
        perms.add(userRole.getRoleName());
        //添加到user的属性当中
        user.setPerms (perms);
        //返回用户信息
        return new SimpleAuthenticationInfo (user,user.getPassword(),getRealmName ());
    }
}
